<template>
  <div class="settings-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">Your Settings</h1>

          <form @submit.prevent="handleSubmit">
            <fieldset>
              <fieldset class="form-group">
                <input
                  v-model="form.image"
                  class="form-control"
                  type="text"
                  placeholder="URL of profile picture"
                />
              </fieldset>
              <fieldset class="form-group">
                <input
                  v-model="form.username"
                  class="form-control form-control-lg"
                  type="text"
                  placeholder="Your Name"
                />
              </fieldset>
              <fieldset class="form-group">
                <textarea
                  v-model="form.bio"
                  class="form-control form-control-lg"
                  rows="8"
                  placeholder="Short bio about you"
                ></textarea>
              </fieldset>
              <fieldset class="form-group">
                <input
                  v-model="form.email"
                  class="form-control form-control-lg"
                  type="text"
                  placeholder="Email"
                />
              </fieldset>
              <fieldset class="form-group">
                <input
                  v-model="form.password"
                  class="form-control form-control-lg"
                  type="password"
                  placeholder="Password"
                />
              </fieldset>
              <button class="btn btn-lg btn-primary pull-xs-right">
                Update Settings
              </button>
            </fieldset>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { updateUser } from '@/api/user'

export default {
  middleware: 'auth',
  name: 'SettingIndex',
  asyncData({ store }) {
    const { user } = store.state
    return {
      form: {
        username: user.username,
        bio: user.bio,
        image: user.image,
        email: user.email,
        password: '',
      },
    }
  },
  methods: {
    handleSubmit() {
      if (this.form.username === '') return
      const form = { ...this.form }
      if (form.email === '') delete form.email
      if (form.password === '') delete form.password
      updateUser(form)
        .then(({ user }) => {
          this.$store.dispatch('login', user)
        })
        .then(() => {
          this.$router.push('/login')
        })
    },
  },
}
</script>

<style></style>
